
<template>
  <a-upload-dragger
    v-bind="$attrs"
    :multiple="multiple"
    :accept="accept"
    :beforeUpload="beforeUpload"
    :fileList="fileList"
    @change="handleChange"
  >
    <p class="ant-upload-drag-icon">
      <a-icon type="inbox" />
    </p>
    <p class="ant-upload-text">点击或拖拽文件到此处上传</p>
    <p class="ant-upload-hint">
      支持{{ accept }}格式，单个文件不超过10MB，最多上传{{ maxCount }}个文件
    </p>
  </a-upload-dragger>
</template>

<script>
export default {
  name: 'DragUpload',
  props: {
    accept: {
      type: String,
      default: '*'
    },
    maxCount: {
      type: Number,
      default: 1
    }
  },
  data () {
    return {
      fileList: []
    }
  },
  computed: {
    multiple () {
      return this.maxCount > 1
    }
  },
  methods: {
    beforeUpload (file) {
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.error('文件大小不能超过10MB!')
        return false
      }
      const accept = this.accept.split(',')
      const curType = file.name.split('.').pop()
      if (accept[0] !== '*' && !accept.includes('.' + curType)) {
        this.$message.error(`仅支持上传${this.accept}格式文件!`)
        return false
      }
      if (this.fileList.length >= this.maxCount) {
        this.$message.error(`最多只能上传${this.maxCount}个文件!`)
        return false
      }
      return false // 阻止自动上传
    },
    handleChange (info) {
      let fileList = [...info.fileList]
      fileList = fileList.slice(-this.maxCount)
      this.fileList = fileList
      this.$emit('change', fileList)
    }
  }
}
</script>
